package com.wpam.scrabble.mobile;

import java.io.Serializable;
import java.util.ArrayList;

import com.wpam.scrabble.mobile.communication.CommunicationManager;

public class ScoreBoard implements Serializable {
	
	private static final long serialVersionUID = 1L;
	
	private Integer currentPlayer_;
	private ArrayList<UserStats> players_;
	
	public ScoreBoard() {
		
		currentPlayer_ = null;
		players_ = new ArrayList<UserStats>();
	}
	
	public ScoreBoard(ArrayList<String> playerNames) {
		
		currentPlayer_ = 0;
		players_ = new ArrayList<UserStats>();
		for (String name : playerNames)
			players_.add(new UserStats(name));
	}
	
	public String getCurrentPlayer() {
		return players_.get(currentPlayer_).getName();
	}

	public void addPlayer(String name) {
		
		players_.add(new UserStats(name));
		if (players_.size() == 1)
			currentPlayer_ = 0;
	}
	
	public void addPlayerPoints(String name, int points) {

		for(UserStats user : players_) {
			if (user.getName().equals(name)) {
				user.setPoints(user.getPoints() + points);
				return;
			}
		}
	}
	
	public int getPlayerPoints(String name) {
		
		for(UserStats user : players_) {
			if (user.getName().equals(name))
				return user.getPoints();
		}
		return 0;
	}
	
	public void setPlayerDone(String name) {
		
		for(UserStats user : players_) {
			if (user.getName().equals(name))
				user.setDone(true);
		}
	}
	
	public void nextTurn() {
		
		currentPlayer_ = (currentPlayer_ + 1) % players_.size();
		while (players_.get(currentPlayer_).isDone() || !players_.get(currentPlayer_).isConnected())
			currentPlayer_ = (currentPlayer_ + 1) % players_.size();
	}

	public boolean isEverybodyDone() {

		int playersDone = 0;
		for (UserStats user : players_)
			playersDone += user.isDone() ? 1 : 0;
		return playersDone + 1 >= players_.size();
	}

	public ArrayList<String> getPlayerNames() {
		
		ArrayList<String> names = new ArrayList<String>();
		for (UserStats user : players_)
			names.add(user.getName());
		return names;
	}

	public ArrayList<Integer> getPoints() {

		ArrayList<Integer> points = new ArrayList<Integer>();
		for (UserStats user : players_)
			points.add(user.getPoints());
		return points;
	}
	
	private class UserStats implements Serializable {

		private static final long serialVersionUID = 1L;
		
		private String name_;
		private int points_;
		private boolean done_;
		
		public UserStats(String name) {
			
			this.name_ = name;
			this.points_ = 0;
			this.done_ = false;
		}

		public int getPoints() {
			return points_;
		}

		public void setPoints(int points) {
			this.points_ = points;
		}

		public boolean isDone() {
			return done_;
		}

		public void setDone(boolean done) {
			this.done_ = done;
		}

		public String getName() {
			return name_;
		}

		public boolean isConnected() {
			return (CommunicationManager.getMyName().equals(name_) ? true : CommunicationManager.getInstance().isPlayerConnected(name_));
		}
	}
}
